package cat.joronya.supermanager.service;

import org.apache.http.impl.client.DefaultHttpClient;

import android.app.IntentService;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.market.MarketProvider;
import cat.joronya.supermanager.privateleague.PrivateLeagueProvider;
import cat.joronya.supermanager.team.MyTeamsProvider;

/**
 * Reb Intents del SupermanagerHelper i els va encuant
 * i executant ordenadament en un thread apart per no
 * bloquejar aqui.
 * 
 * @author pol
 */
public class SupermanagerService extends IntentService
{
	// tag per log
	private static final String TAG = "supermanager";
	
	// guardem la sessio en tota la tongada de peticions a la
	// mateixa instancia de service
	DefaultHttpClient client = null;
	Integer jornada = null;
	Messenger messenger = null;
	
	public SupermanagerService()
	{
		super("SupermanagerService");
	}
	
	/**
	 * Respon a les diferents demandes de les Activities, el IntentService
	 * ja s'encarrega de la cua i de passar-nos intents un a un. Tambe fa
	 * que s'executi en un worker thread.
	 */
	@Override
	protected void onHandleIntent(Intent intent) 
	{
		// mirem que ens demanen executar
		Uri uri = intent.getData();
		
		// uep, no tenim uri?? no cal fer res!
		if( !"login".equals(intent.getAction()) && uri == null)
		{
			Log.d(TAG, "no estem al login ni ens passen Uri, llavors no fem res");
			return;
		}
		
		// recuperem el messenger per notificar l'activity que ens ha cridat
		messenger = (Messenger)intent.getExtras().get("cat.joronya.supermanager.messenger"); 
		

		// Cal fer init i login en dos casos:
		// -si es la primera accio i no tenim sessio
		// -si es el login 
		if( client == null || "login".equals(intent.getAction()) )
		{
			// inicialitzem la sessio
			InitSync initSync = new InitSync(this);
			client = initSync.execute();
			
			// si dona error de conectivitat
			if( initSync.status == Supermanager.CONNECTIVITY_ERROR_STATUS )
			{
				// cridar el handler amb el status de connectivity error
				Message msg = Message.obtain(); 
                Bundle data = new Bundle(); 
                data.putInt(Supermanager.STATUS_MESSAGE, Supermanager.CONNECTIVITY_ERROR_STATUS); 
                msg.setData(data); 
                
                try{ 
                    messenger.send(msg); 
                }catch(RemoteException e){ 
                    Log.e(TAG, "Error sending auth error to Activity caller"); 
                } 
                
				Log.e(TAG,"Connectivity error!");
				return;
			}
			else if( initSync.status == Supermanager.CLOSED_STATUS )
			{
				// cridar el handler amb el status de closed error
				Message msg = Message.obtain(); 
                Bundle data = new Bundle(); 
                data.putInt(Supermanager.STATUS_MESSAGE, Supermanager.CLOSED_STATUS); 
                msg.setData(data); 
                
                try{ 
                    messenger.send(msg); 
                }catch(RemoteException e){ 
                    Log.e(TAG, "Error sending auth error to Activity caller"); 
                } 
                
				Log.e(TAG,"Close web error!");
				return;
			}
			else if( initSync.status == Supermanager.OTHER_ERROR_STATUS )
			{
				// cridar el handler amb el status de other unknown error
				Message msg = Message.obtain(); 
                Bundle data = new Bundle(); 
                data.putInt(Supermanager.STATUS_MESSAGE, Supermanager.OTHER_ERROR_STATUS); 
                msg.setData(data); 
                
                try{ 
                    messenger.send(msg); 
                }catch(RemoteException e){ 
                    Log.e(TAG, "Error sending auth error to Activity caller"); 
                } 
                
				Log.e(TAG,"Other error!");
				return;
			}
			
			if( client == null )
			{
				Log.e(TAG, "Error initializing network connection");
				return;
			}
			
			// recuperem username i password pel login
			String username = intent.getStringExtra("cat.joronya.supermanager.login.username");
			String password = intent.getStringExtra("cat.joronya.supermanager.login.password");

			// fem login
			LoginSync loginSync = new LoginSync(this, client);
			loginSync.execute(username,password);
			
			// si dona error d'AUTH no guardem i mostrem Toast d'error
			if( loginSync.status == Supermanager.AUTH_ERROR_STATUS )
			{
				// cridar el handler amb el status d'auth error
				Message msg = Message.obtain(); 
                Bundle data = new Bundle(); 
                data.putInt(Supermanager.STATUS_MESSAGE, loginSync.status); 
                msg.setData(data); 
                
                try{ 
                    messenger.send(msg); 
                }catch(RemoteException e){ 
                    Log.e(TAG, "Error sending auth error to Activity caller"); 
                } 
                
				Log.e(TAG,"Authentication error!");
				return;
			}
			else if( loginSync.status == Supermanager.CONNECTIVITY_ERROR_STATUS )
			{
				// cridar el handler amb el status de connectivity error
				Message msg = Message.obtain(); 
                Bundle data = new Bundle(); 
                data.putInt(Supermanager.STATUS_MESSAGE, Supermanager.CONNECTIVITY_ERROR_STATUS); 
                msg.setData(data); 
                
                try{ 
                    messenger.send(msg); 
                }catch(RemoteException e){ 
                    Log.e(TAG, "Error sending auth error to Activity caller"); 
                } 
                
				Log.e(TAG,"Connectivity error!");
				return;
			}
			else if( loginSync.status == Supermanager.OTHER_ERROR_STATUS )
			{
				// cridar el handler amb el status de other unknown error
				Message msg = Message.obtain(); 
                Bundle data = new Bundle(); 
                data.putInt(Supermanager.STATUS_MESSAGE, Supermanager.OTHER_ERROR_STATUS); 
                msg.setData(data); 
                
                try{ 
                    messenger.send(msg); 
                }catch(RemoteException e){ 
                    Log.e(TAG, "Error sending auth error to Activity caller"); 
                } 
                
				Log.e(TAG,"Other error!");
				return;
			}
			else if( loginSync.status == Supermanager.OPEN_NO_CHANGES_STATUS )
			{
				// nomes notifiquem de l'estat si feiem login, sino continuem
				if( "login".equals(intent.getAction()) )
				{
					// cridar el handler amb el status de open with no changes
					Message msg = Message.obtain(); 
					Bundle data = new Bundle(); 
					data.putInt(Supermanager.STATUS_MESSAGE, Supermanager.OPEN_NO_CHANGES_STATUS); 
					msg.setData(data); 
                
					try{ 
						messenger.send(msg); 
					}catch(RemoteException e){ 
						Log.e(TAG, "Error sending auth error to Activity caller"); 
					} 
				}
				Log.d(TAG,"Status Open with no changes");
			}
			else if( loginSync.status == Supermanager.OPEN_STATUS )
			{
				// nomes notifiquem de l'estat si feiem login, sino continuem
				if( "login".equals(intent.getAction()) )
				{
					// cridar el handler amb el status de open
					Message msg = Message.obtain(); 
					Bundle data = new Bundle(); 
					data.putInt(Supermanager.STATUS_MESSAGE, Supermanager.OPEN_STATUS); 
					msg.setData(data); 
                
					try{ 
						messenger.send(msg); 
					}catch(RemoteException e){ 
						Log.e(TAG, "Error sending auth error to Activity caller"); 
					} 
				}
				Log.d(TAG,"Status Open");
			}

			jornada = new Integer(loginSync.jornada);
			Log.d(TAG,"LoginSyn.jornada: "+jornada);

			// altrament guardem dades home i estat
			loginSync.onPostExecute(Supermanager.Home.CONTENT_URI);
			
			// si nomes feiem login sortiem
			if( "login".equals(intent.getAction()) )
				return;
		}
		
		// mirem si es algo referent a les lligues privades
		// uri de /privateleagues -> nomes updatem els llistat, no mirem action
		if( PrivateLeagueProvider.uriMatcher.match(uri) == PrivateLeagueProvider.PRIVATE_LEAGUES )
		{
			// get private leagues
			PrivateLeaguesSync plSync = new PrivateLeaguesSync(this, client);
			// si no hi ha error guardem a db
			plSync.execute();
			
			if( plSync.status == Supermanager.CONNECTIVITY_ERROR_STATUS )
			{
				// cridar el handler amb el status de connectivity error
				Message msg = Message.obtain(); 
                Bundle data = new Bundle(); 
                data.putInt(Supermanager.STATUS_MESSAGE, Supermanager.CONNECTIVITY_ERROR_STATUS); 
                msg.setData(data); 
                
                try{ 
                    messenger.send(msg); 
                }catch(RemoteException e){ 
                    Log.e(TAG, "Error sending auth error to Activity caller"); 
                } 
                
				Log.e(TAG,"Connectivity error!");
				return;
			}
			else if( plSync.status == Supermanager.OTHER_ERROR_STATUS )
			{
				// cridar el handler amb el status de other unknown error
				Message msg = Message.obtain(); 
                Bundle data = new Bundle(); 
                data.putInt(Supermanager.STATUS_MESSAGE, Supermanager.OTHER_ERROR_STATUS); 
                msg.setData(data); 
                
                try{ 
                    messenger.send(msg); 
                }catch(RemoteException e){ 
                    Log.e(TAG, "Error sending auth error to Activity caller"); 
                } 
                
				Log.e(TAG,"Other error!");
				return;
			}
			else if( plSync.status == Supermanager.PRIVATE_LEAGUES_PARSED_OK )
			{
				try
				{
					plSync.onPostExecute(intent.getData());

					// cridar el handler amb el status private leagues parsed successfully
					Message msg = Message.obtain(); 
	                Bundle data = new Bundle(); 
	                data.putInt(Supermanager.STATUS_MESSAGE, Supermanager.PRIVATE_LEAGUES_PARSED_OK); 
	                msg.setData(data); 
	                
	                try{ 
	                    messenger.send(msg); 
	                }catch(RemoteException e){ 
	                    Log.e(TAG, "Error sending auth error to Activity caller"); 
	                } 
	                
					Log.d(TAG,"Private leagues parsed successfully!");
				}
				catch(Exception e)
				{
					// cridar el handler amb el status de other unknown error
					Message msg = Message.obtain(); 
	                Bundle data = new Bundle(); 
	                data.putInt(Supermanager.STATUS_MESSAGE, Supermanager.OTHER_ERROR_STATUS); 
	                msg.setData(data); 
	                
	                try{ 
	                    messenger.send(msg); 
	                }catch(RemoteException re){ 
	                    Log.e(TAG, "Error sending auth error to Activity caller"); 
	                } 
	                
					Log.e(TAG,"Other error!");
				}
				
				return;
			}
		}
		
		// mirem si es algo referent al mercat
		// uri de /market -> nomes updatem els llistat, no mirem action
		if( MarketProvider.uriMatcher.match(uri) == MarketProvider.MARKET_PLAYERS )
		{
			// get market players
			Log.d(TAG,"MarketSync amb jornada: "+jornada);
			MarketSync marketSync = new MarketSync(this, client, jornada);
			// si no hi ha error guardem a db
			marketSync.execute();
			
			if( marketSync.status == Supermanager.CONNECTIVITY_ERROR_STATUS )
			{
				// cridar el handler amb el status de connectivity error
				Message msg = Message.obtain(); 
                Bundle data = new Bundle(); 
                data.putInt(Supermanager.STATUS_MESSAGE, Supermanager.CONNECTIVITY_ERROR_STATUS); 
                msg.setData(data); 
                
                try{ 
                    messenger.send(msg); 
                }catch(RemoteException e){ 
                    Log.e(TAG, "Error sending auth error to Activity caller"); 
                } 
                
				Log.e(TAG,"Connectivity error!");
				return;
			}
			else if( marketSync.status == Supermanager.OTHER_ERROR_STATUS )
			{
				// cridar el handler amb el status de other unknown error
				Message msg = Message.obtain(); 
                Bundle data = new Bundle(); 
                data.putInt(Supermanager.STATUS_MESSAGE, Supermanager.OTHER_ERROR_STATUS); 
                msg.setData(data); 
                
                try{ 
                    messenger.send(msg); 
                }catch(RemoteException e){ 
                    Log.e(TAG, "Error sending auth error to Activity caller"); 
                } 
                
				Log.e(TAG,"Other error!");
				return;
			}
			else if( marketSync.status == Supermanager.MARKET_PARSED_OK )
			{
				try
				{
					marketSync.onPostExecute(intent.getData());

					// cridar el handler amb el status market parsed successfully
					Message msg = Message.obtain(); 
	                Bundle data = new Bundle(); 
	                data.putInt(Supermanager.STATUS_MESSAGE, Supermanager.MARKET_PARSED_OK); 
	                msg.setData(data); 
	                
	                try{ 
	                    messenger.send(msg); 
	                }catch(RemoteException e){ 
	                    Log.e(TAG, "Error sending auth error to Activity caller"); 
	                } 
	                
					Log.d(TAG,"Market data parsed successfully!");
				}
				catch(Exception e)
				{
					// cridar el handler amb el status de other unknown error
					Message msg = Message.obtain(); 
	                Bundle data = new Bundle(); 
	                data.putInt(Supermanager.STATUS_MESSAGE, Supermanager.OTHER_ERROR_STATUS); 
	                msg.setData(data); 
	                
	                try{ 
	                    messenger.send(msg); 
	                }catch(RemoteException re){ 
	                    Log.e(TAG, "Error sending auth error to Activity caller"); 
	                } 
	                
					Log.e(TAG,"Other error!");
				}
				
				return;
			}
		}

		// mirem si es algo referent als equips
		// uri de /teams -> nomes updatem els llistat, no mirem action
		if( MyTeamsProvider.uriMatcher.match(uri) == MyTeamsProvider.MY_TEAMS )
		{
			// get my teams
			MyTeamsSync myTeamsSync = new MyTeamsSync(this, client);
			// si no hi ha error guardem a db
			myTeamsSync.execute();
			
			if( myTeamsSync.status == Supermanager.CONNECTIVITY_ERROR_STATUS )
			{
				// cridar el handler amb el status de connectivity error
				Message msg = Message.obtain(); 
                Bundle data = new Bundle(); 
                data.putInt(Supermanager.STATUS_MESSAGE, Supermanager.CONNECTIVITY_ERROR_STATUS); 
                msg.setData(data); 
                
                try{ 
                    messenger.send(msg); 
                }catch(RemoteException e){ 
                    Log.e(TAG, "Error sending auth error to Activity caller"); 
                } 
                
				Log.e(TAG,"Connectivity error!");
				return;
			}
			else if( myTeamsSync.status == Supermanager.OTHER_ERROR_STATUS )
			{
				// cridar el handler amb el status de other unknown error
				Message msg = Message.obtain(); 
                Bundle data = new Bundle(); 
                data.putInt(Supermanager.STATUS_MESSAGE, Supermanager.OTHER_ERROR_STATUS); 
                msg.setData(data); 
                
                try{ 
                    messenger.send(msg); 
                }catch(RemoteException e){ 
                    Log.e(TAG, "Error sending auth error to Activity caller"); 
                } 
                
				Log.e(TAG,"Other error!");
				return;
			}
			else if( myTeamsSync.status == Supermanager.MY_TEAMS_PARSED_OK )
			{
				try
				{
					myTeamsSync.onPostExecute(intent.getData());

					// cridar el handler amb el status my teams parsed successfully
					Message msg = Message.obtain(); 
	                Bundle data = new Bundle(); 
	                data.putInt(Supermanager.STATUS_MESSAGE, Supermanager.MY_TEAMS_PARSED_OK); 
	                msg.setData(data); 
	                
	                try{ 
	                    messenger.send(msg); 
	                }catch(RemoteException e){ 
	                    Log.e(TAG, "Error sending auth error to Activity caller"); 
	                } 
	                
					Log.d(TAG,"My teams parsed successfully!");
				}
				catch(Exception e)
				{
					// cridar el handler amb el status de other unknown error
					Message msg = Message.obtain(); 
	                Bundle data = new Bundle(); 
	                data.putInt(Supermanager.STATUS_MESSAGE, Supermanager.OTHER_ERROR_STATUS); 
	                msg.setData(data); 
	                
	                try{ 
	                    messenger.send(msg); 
	                }catch(RemoteException re){ 
	                    Log.e(TAG, "Error sending auth error to Activity caller"); 
	                } 
	                
					Log.e(TAG,"Other error!");
				}
				
				return;
			}
		}
		
	}
	
}